package com.foreknow.web;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.foreknow.entity.User;
import com.foreknow.service.UserService;
import com.foreknow.utils.Constance;
import com.foreknow.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController{

  @Autowired
  private UserService userService;
  @RequestMapping(value = "/login",method = RequestMethod.POST)
  @ResponseBody
  public String login(@RequestBody Map<String,Object> para) throws JsonProcessingException {
//    获取用户登录信息
    String username=(String)para.get("username");
    String password=(String)para.get("password");

    User user = new User();
    user.setUsername(username);
    user.setPassword(password);
    User loginuser = userService.login(user);

    HashMap<String,Object> hs=new HashMap<>();
    ObjectMapper objectMapper=new ObjectMapper();

    //登录成功
    if (loginuser!= null) {
      String token =  TokenUtil.sign(user);
//           token=  user.setToken(token);
      hs.put("token", token);
      hs.put("data", user);
      hs.put("meta", new Constance("msg", 200));
    } else {
      hs.put("meta", new Constance("msg", 404));
    }
    return objectMapper.writeValueAsString(hs);
  }

  @RequestMapping(value = "/test", method = RequestMethod.POST)
  @ResponseBody
  public String test(@RequestBody Map<String, Object> para) throws JsonProcessingException {
    HashMap<String, Object> hs = new HashMap<>();
    hs.put("data", "data");
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.writeValueAsString(hs);
  }

}
